﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

namespace FileTranslator
{
    public abstract class Exporter
    {
        public string TargetPath { get; set; }
        public DataTableWrapper DtWrapper { get; set;}

        public Exporter(string path, DataTableWrapper dtw)
        {
            TargetPath = path;
            DtWrapper = dtw;
        }

        public Exporter()
        {
            TargetPath = null;
            DtWrapper = null;
        }

        public void Export()
        {
            if (DtWrapper == null)
            {
                // TODO: log
                throw new System.NullReferenceException("DataTableWrapper can not be NULL");
            }

            if (VerifyPathValid() == false)
            {
                // TODO: log
                throw new System.IO.FileNotFoundException("Path Invalid");
            }

            if ( VerifyFileExist() == true)
            {
                // TODO : log
                throw new System.IO.IOException("Export file already exists");
            }

            BeforeExport();
            DoExport();
            AfterExport();
        }

        private bool VerifyFileExist()
        {
            return !(TargetPath == null || System.IO.File.Exists(TargetPath) == false);
        }

        private bool VerifyPathValid()
        {
            if (TargetPath == null)
            {
                return false;
            }

            char[] invalidPathChars = Path.GetInvalidPathChars();
            foreach (char c in invalidPathChars)
            {
                if (TargetPath.Contains(c) == true)
                {
                    return false;
                }
            }

            return true;
        }

        protected virtual void BeforeExport() { }
        protected virtual void AfterExport() { }

        protected abstract void DoExport();
    }

    public class CsvFileExport : Exporter
    {
        public CsvFileExport() { }
        public CsvFileExport(string path, DataTableWrapper dtw)
            : base(path, dtw)
        {}

        protected override void DoExport()
        {
            if (DtWrapper.InnerTable == null)
            {
                // TODO: log

                throw new NullReferenceException("Data Table Null");
            }

            CsvHelper.LocalTblToCsv(DtWrapper.InnerTable.ToTable(), TargetPath);
        }
    }
}
